# coding:utf8

import json

from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListAPIView, CreateAPIView, RetrieveAPIView, DestroyAPIView, \
    UpdateAPIView, RetrieveUpdateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.response import Response
from rest_framework import mixins, status
from BookTest.models import BookInfo
from BookTest.serializers import BookInfoSerializer, BookReadSerializer

# class BookListView(APIView):
#     """APIView是所有视图类的基类，继承自Django的View父类"""
#     def get(self, request):
#         queryset = BookInfo.objects.all()
#         serializer = BookInfoSerializer(queryset, many=True)
#         return Response(data=serializer.data)

# class BookListView(mixins.ListModelMixin, GenericAPIView):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer
#
#     def get(self, request):
#         return self.list(request)

# class BookListView(ListAPIView, CreateAPIView):
#     """
#     1.CreateAPIView 继承自CreateModelMixin和GenericMixin
#     2.ListAPIView 提供get方法，继承自ListModelMixin
#
#     """
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer


# class BookDetailView(GenericAPIView):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer
#
#     def get(self, request, pk):
#         book = self.get_object()
#         serializer = self.get_serializer(book)
#         return Response(serializer.data)
# class BookDetailView(RetrieveAPIView, DestroyAPIView):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer
#
#
# class BookChangeView(UpdateAPIView):
#     """
#     UpdateAPIVIew:提供put和patch方法，继承自GenericAPIView,UpdateModelMixin
#     """
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer
#
#
# class BookGetChangeView(RetrieveUpdateAPIView):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer
#
#
# class BookIndexView(RetrieveUpdateDestroyAPIView):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookInfoSerializer


from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny, BasePermission
from rest_framework.throttling import UserRateThrottle


def index(request):
    # 将my_task任务加入到celery队列中
    # 如果my_task函数有参数，可通过delay()传递
    # 例如 my_task(a, b), my_task.delay(10, 20)
    from .tasks import my_task
    my_task.delay()

    return HttpResponse("<h1>服务器返回响应内容!</h1>")


class MyPermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        # 是否可以访问对象，view表示视图，obj为数据对象
        return False


class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer
    # permission_classes = [IsAuthenticated, ]
    # permission_classes = [MyPermission]
    # filter_fields = ('btitle', 'bread')

    # def get_permissions(self):
    #     if self.action == 'read':
    #         return [IsAuthenticated(), ]
    #     else:
    #         return [AllowAny()]

    def get_serializer_class(self):
        if self.action == 'read':
            return BookReadSerializer
        else:
            return BookInfoSerializer

    def get(self, request, *args, **kwargs):
        print("进入books/视图")
        return Response(status=status.HTTP_200_OK)

    # detail为False，表示不需要处理具体的BookInfo对象
    @action(methods=['get'], detail=False)
    def latest(self, request):
        from django.db import DatabaseError
        raise DatabaseError
        book = BookInfo.objects.latest('id')
        serializer = self.get_serializer(instance=book)
        return Response(serializer.data)

    # detail为True，表示要处理具体与Pk主键对应的BookInfo对象
    @action(methods=['put'], detail=True)
    def read(self, request, pk):
        book = self.get_object()
        # book.read = request.data.get('read')
        # book.save()
        # serializer = self.get_serializer(book)
        # 序列化时将模型类对象传入instance对象
        # 反序列化时，将要被反序列化的数据传入data参数
        serializer = self.get_serializer(instance=book, data=request.data, context={'context_test': 'test'})
        serializer.is_valid(raise_exception=True)
        serializer.save(owner=request.user)
        return Response(serializer.data)
